package com.interceptor;

import com.domain.LoginUser;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器：拦截未登录的操作
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //在拦截点执行前进行拦截，如果然后true则不执行拦截点之后的操作
        LoginUser user = (LoginUser) request.getSession().getAttribute("user");
        if (user != null){
            //有登录则不拦截
            return true;
        }else {
            //进行拦截
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //在处理过程中进行拦截
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //处理完毕后，返回时拦截
    }
}
